"ui"

// 获取屏幕高度和宽度（px）
let screenWidth = device.width;
let screenHeight = device.height;

let analyseSartY = 230;
let analyseEndY = Infinity;
let analyseThreshold = 100;
// 配置 API 信息（请替换为实际接口地址和密钥）
const API_URL = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"; // 豆包对话接口地址
const MODEL = "doubao-1-5-pro-32k-250115"; // 固定使用的模型
let currentMsgHistory = []
// 第一步：补充 startsWith 兼容方法（最顶部）

// ===== 配置区 =====
let config = {
  doubaoApiKey: "", // 替换为豆包API密钥
  floatBtnSize: 40,             // 悬浮按钮大小
  ocrAccuracy: 0.8,             // OCR识别阈值
  replyCount: 3,                 // 生成回复数量
  replyType: "高情商",
  replyCenter: "你好呀",
  replyTarget:'女朋友'
};

// ===== 全局变量 =====
let floatWindow = null;       // 悬浮窗实例
let replyWindow = null;       // 回复展示窗
let isListening = false;      // 监听状态

// ===== 工具函数 =====
/**
 * 初始化悬浮按钮
 */
function initFloatButton() {
  // 检查悬浮窗权限
  if (!floaty.checkPermission()) {
    toast("本脚本需要悬浮窗权限来显示悬浮窗，请在随后的界面中允许并重新运行本脚本。");
    floaty.requestPermission();
    exit();
  }

  if (floatWindow) {
    return;
  }



  // 创建悬浮窗XML结构
  floatWindow = floaty.window(`
  <frame>
  
   
    <img 
      id="floatBtn" 
      w="${config.floatBtnSize}" 
      h="${config.floatBtnSize}" 
      src="http://39.105.231.80:9900/keji.png"
    />

    <img 
      id="thinking" 
      w="${config.floatBtnSize}" 
      h="${config.floatBtnSize}" 
      visibility="gone"
      src="http://39.105.231.80:9900/loading.png"
    />
  </frame>
`);


  // 禁用窗口调整功能，保持界面整洁
  //  floatWindow.setAdjustEnabled(true);
  // 设置悬浮窗关闭时退出脚本
  floatWindow.exitOnClose();

  // 空定时器保持脚本运行，防止悬浮窗被关闭
  setInterval(() => { }, 1000);

  // 获取悬浮窗内的frame组件
  let floatBtn = floatWindow.floatBtn;

  // 初始位置
  let x = 50, y = 200;
  floatWindow.setPosition(x, y);

  // 拖动变量
  let lastX, lastY;

  // 触摸事件监听（兼容写法）
  floatBtn.setOnTouchListener(function (view, event) {
    switch (event.getAction()) {
      case event.ACTION_DOWN:
        lastX = event.getRawX();
        lastY = event.getRawY();
        return true;
      case event.ACTION_MOVE:
        floatWindow.setPosition(
          floatWindow.getX() + (event.getRawX() - lastX),
          floatWindow.getY() + (event.getRawY() - lastY)
        );
        lastX = event.getRawX();
        lastY = event.getRawY();
        return true;
      case event.ACTION_UP:
        if (event.getEventTime() - event.getDownTime() < 300) {
          onFloatButtonClick();
        }
        return true;
    }
    return false;
  });
}
function onFloatButtonClick() {

  if (floatWindow.thinking.getVisibility() === 0) { // 0表示VISIBLE
    return; // 如果进度条正在显示，则忽略点击
  }
  if (replyWindow) {
    replyWindow.close();
    replyWindow = null;
  }

  // 显示进度条
  floatWindow.thinking.setVisibility(0); // 0表示VISIBLE
  floatWindow.floatBtn.setVisibility(8); // 0表示VISIBLE

  //floatWindow.floatBtn.setEnabled(false); // 禁用按钮点击


  showReplyWindow("");
  ui.run(() => {
    floatWindow.thinking.setVisibility(8); // 0表示VISIBLE
    floatWindow.floatBtn.setVisibility(0); // 0表
  })
}

/**
 * 调用豆包AI生成回复
 */
function generateAIReply() {
  return new Promise((resolve, reject) => {
    if (!config.doubaoApiKey) {
      reject(new Error("请先配置豆包API密钥"));
      return;
    }
    let {replyTarget,replyCenter,replyType} = config;
    const prompt = `${replyTarget}说${replyCenter}，我该怎么${replyType}的回复,(每条回复10-40字，用####隔开，尽量从不同角度，提供十条,不要带序号)`;

    chatWithDoubao(prompt, function (err, reply, usedModel) {
      if (err) {
        toastLog("错误：" + err);
        console.error("错误：", err);
      } else {
        resolve(reply)
      }
    });
  });
}




/**
 * 显示回复窗口
 */
function showReplyWindow(replies) {
  let repliesArray = replies.split("####").filter(item => item && item.trim())
  console.log("1111",repliesArray)
  // 1. 创建主窗口（半透明背景，文字保持清晰）

  
  replyWindow = floaty.window(
    `<vertical 
          id="replyWindowContent"
          bg="#CCFFFFFF"
          h="auto" 
          padding="10" 
          radius="8"
      >
          <frame  w="*">
            <text 
                text="智能回复" 
                size="14" 
                color="#000000"
                margin="0 0 8 0"
                bold="true"
                w="auto"
            />
            <img id="closeIcon"  src="@drawable/ic_clear_black_48dp"  w="20" h="20" bg="?selectableItemBackgroundBorderless" layout_gravity="right" />
          </frame>
         <linear>
            <text w="75" gravity="center" color="#111111" size="12">回复对象:</text>
            <input id="reply_target" w="*" h="40" size="12" text="${config.replyTarget}"  focusable="true"/>
        </linear>
        <linear>
            <text w="75" gravity="center" color="#111111" size="12">回复要求:</text>
            <input id="reply_type" w="*" h="40" size="12" text="${config.replyType}" />
        </linear>
        <vertical>
            <linear>
                <text w="75" gravity="center" color="#111111" size="12">回复句子:</text>
                <button text="粘贴" w="auto" h="auto" size="12" id="reply_center_btn"/>
            </linear>
            <linear 
              w="*" 
              h="auto" 
              background="#E0E0E0"
              padding="2"
              margin="4">
                <input id="reply_center" gravity="top" w="*" h="70" text="${config.replyCenter}"  size="12" lines="2"/>
            </linear>
        </vertical>
        
          <scroll  w="*" h="300">
           <vertical id="replyContainer" w="*" h="300">
                  ${repliesArray.map((reply, index) => (
                    `<card w="*" h="40" margin="10 5" cardCornerRadius="2dp" id="reply_${index}"
                          cardElevation="1dp" gravity="center_vertical">
                          <vertical padding="15 8" h="auto">
                              <text  text="${index+1}.${reply}" textColor="#222222" textSize="10sp"/>
                          </vertical>
                          <View bg="${getRandomColor()}" h="*" w="10"/>
                     </card>`
                  ))}
            </vertical>
          </scroll>
         

          <frame>
              <button 
                id="refresh" 
                text="搜索" 
                w="auto" 
                marginLeft="25"
                textColor="#FFFFFF"
              />
              <button 
                layout_gravity="right"
                marginRight="25"
                id="btnClose" 
                text="关闭" 
                style="Widget.AppCompat.Button.Colored" 
                w="auto"
              />
          </frame>
      </vertical>`
  );
  // if(reply) {
  //   replyWindow.replyText.setText(reply);
  // }

replyWindow.closeIcon.on("click", () => {
  replyWindow.close();
  replyWindow = null
});
replyWindow.reply_target.on("key", function(keyCode, event){
    if(event.getAction() == event.ACTION_DOWN && keyCode == keys.back){
        replyWindow.disableFocus();
        event.consumed = true;
    }
});
replyWindow.reply_type.on("key", function(keyCode, event){
  if(event.getAction() == event.ACTION_DOWN && keyCode == keys.back){
      replyWindow.disableFocus();
      event.consumed = true;
  }
});
replyWindow.reply_center.on("key", function(keyCode, event){
  if(event.getAction() == event.ACTION_DOWN && keyCode == keys.back){
      replyWindow.disableFocus();
      event.consumed = true;
  }
});

replyWindow.reply_target.on("touch_down", ()=>{
  replyWindow.requestFocus();
  replyWindow.reply_target.requestFocus();
});
replyWindow.reply_type.on("touch_down", ()=>{
  replyWindow.requestFocus();
  replyWindow.reply_type.requestFocus();
});
replyWindow.reply_center.on("touch_down", ()=>{
  replyWindow.requestFocus();
  replyWindow.reply_center.requestFocus();
});

replyWindow.reply_center_btn.on("click", () => {
  //读出剪切板的第一句，进行粘贴
  replyWindow.requestFocus();
  replyWindow.reply_center.requestFocus();
  setTimeout(()=>{
    let text = getClip()
    replyWindow.reply_center.setText(text);
  },100)
});
replyWindow.setSize(screenWidth, screenHeight)
  // 关闭按钮事件
  replyWindow.btnClose.on("click", () => {
    replyWindow.close();
    replyWindow = null
  });
  // 刷新按钮事件
  // 刷新按钮事件（修改后）
  replyWindow.refresh.on("click", () => {
    config.replyCenter = replyWindow.reply_center.text()
    config.replyTarget = replyWindow.reply_target.text()
    config.replyType = replyWindow.reply_type.text()

    replyWindow.refresh.setText("思考中...");
    // 显示加载状态（可选，提升体验）
    if (floatWindow) {
      floatWindow.thinking.setVisibility(0);
      floatWindow.floatBtn.setVisibility(8);
    }

    generateAIReply()
      .then(replies => {
        replyWindow.close();
        replyWindow = null;
        return replies
      })
      .then(replies => {
        showReplyWindow(replies);
      })
      .catch(err => {  // 添加错误捕获
        toast("刷新失败: " + err.message);
      })
      .finally(() => {  // 恢复加载状态
        if (floatWindow) {
          ui.run(() => {
            floatWindow.thinking.setVisibility(8);
            floatWindow.floatBtn.setVisibility(0);
          });
        }
      });
  });
  ui.run(() => {
    // 为每个回复按钮设置点击事件
    repliesArray.forEach((reply, index) => {
      replyWindow[`reply_${index}`].on("click", () => {
        console.log("点击了回复：", reply);
        setClip(reply);
        toast("回复已复制");  // 恢复提示，提升用户体验
      });
    });
  })
  
}


function getRandomColor() {
  // 生成6位随机十六进制数
  const hexChars = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += hexChars.charAt(Math.floor(Math.random() * hexChars.length));
  }
  return color;
}
/**
 * 发送消息给豆包（简化版）
 * @param {string} message 用户消息
 * @param {function} callback 回调函数 (err, reply)
 */
function chatWithDoubao(message, callback) {
  const requestBody = {
    model: MODEL,
    messages: [{ role: "user", content: message }],
    temperature: 0.8
  };

  console.log(`使用模型 ${MODEL} 发送请求:`, message);

  http.postJson(API_URL, requestBody, {
    headers: {
      "Authorization": `Bearer ${config.doubaoApiKey}`,
      "Content-Type": "application/json"
    }
  }, function (response, error) {
    if (error) {
      callback("请求失败: " + error.message, null);
      return;
    }

    try {
      const responseText = response.body.string();
      console.log("豆包响应内容:", responseText);

      const result = JSON.parse(responseText);
      if (response.statusCode === 200 && result.choices && result.choices[0].message) {
        callback(null, result.choices[0].message.content);
      } else {
        callback(`API错误: ${result.error && result.error.message || "未知错误"}`, null);
      }
    } catch (e) {
      callback("解析响应失败: " + e.message, null);
    }
  });
}

let valid = false;
// ===== 主程序 =====
function main() {
  // 校验密钥
  let apiKeyStorage = storages.create("apiKey");
  let apiKeyValue = apiKeyStorage.get("apiKey");
  if (apiKeyValue) {
      // 有存储的密钥，检查有效性
      config.doubaoApiKey = apiKeyValue;
      chatWithDoubao("", function(err) {
          if (err) {
              toast("存储的密钥无效，请重新输入");
              apiKeyStorage.remove("apiKey");
              promptForApiKey();
          } else {
            valid = true
          }
      });
  } else {
      promptForApiKey();
  }
  let controller = setInterval(()=>{
    if(valid){
      onKeyValid()
      console.log("密钥有效,开启程序")
      clearInterval(controller)
    }
  },1000)
}

function promptForApiKey() {
  let input = dialogs.rawInput("请输入你的豆包密钥", "");
  
  // 处理取消情况
  if (input === null) {
      toast("请先输入密钥才能使用");
      promptForApiKey();
      return;
  }
  
  // 确保 input 是字符串
  if (input !== null && input !== undefined) {
      input = String(input); // 强制转换为字符串
  }
  
  if (input && input.trim && input.trim()) {
      config.doubaoApiKey = input.trim();
      //判断 有没有中文，如果有，则提示请输入英文密钥
      if (/[\u4e00-\u9fa5]/.test(input)) {
          toast("密钥无效，请重新输入");
          promptForApiKey();
          return;
      }
      chatWithDoubao("", function(err) {
          if (err) {
              toast("密钥无效，请重新输入");
              promptForApiKey();
          } else {
              storages.create("apiKey").put("apiKey", input.trim());
              valid = true
          }
      });
  } else {
      toast("输入不能为空，请重新输入");
      promptForApiKey();
  }
}

function onKeyValid() {
  // 密钥有效，继续后续逻辑
  // 初始化悬浮按钮
  initFloatButton();
  toast("智能聊天助手已启动");
  // 监听返回键退出
  events.on("back_pressed", function () {
    if (replyWindow) {
      replyWindow.close();
      replyWindow = null;
      return true;
    }
    floatWindow.close();
    floatWindow = null
    engines.myEngine().forceStop();
    return true;
  });
}
main()